package com.blb.zy_community.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * OSS�ļ��ϴ�������
 */
public class OssUtil {

    // Endpoint�Ժ���Ϊ��������Region�밴ʵ�������д��
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    // ���˺�AccessKey������API����Ȩ�ޣ�������ѭ�����ư�ȫ���ʵ����������ʹ��RAM���˺Ž���API���ʻ��ճ���ά�����¼ https://ram.console.aliyun.com ������
    private static String accessKeyId = "LTAI5tLMrMLwQcHpG9f6Qt8k";
    private static String accessKeySecret = "ChliuPga81FAlijeVmwPp34zoinqEq";
    private static String bucketName = "buuker";
    //Ŀ¼��
    public static String dir = "images";

    /**
     * �ļ��ϴ�
     * @param inputStream
     * @param fileName
     */
    public static void upload(InputStream inputStream, String fileName){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.putObject(bucketName,dir +"/"+ fileName,inputStream);
        oss.shutdown();
    }

    /**
     * ����ļ�URL
     * @param fileName
     * @return
     */
    public static String getURL(String fileName){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //���ù���ʱ��
        LocalDateTime time = LocalDateTime.now().plusDays(100);
        Date expiration = Date.from(time.atZone( ZoneId.systemDefault()).toInstant());
        URL url = oss.generatePresignedUrl(bucketName, dir +"/"+ fileName, expiration);
        oss.shutdown();
        return url.toString();
    }

    public static void main(String[] args) throws FileNotFoundException {
        OssUtil.upload(new FileInputStream("C:\\upload\\1.jpg"),"1.jpg");
        System.out.println(OssUtil.getURL("1.jpg"));
    }
}
